/*
 * @Author: your name
 * @Date: 2021-04-03 19:57:29
 * @LastEditTime: 2021-04-15 16:38:27
 * @LastEditors: your name
 * @Description: In User Settings Edit
 * @FilePath: \chronic-back-end\module\userMod\middleware.go
 */
package userMod

import (
	"chronic/common"
	"net/http"

	"github.com/gin-gonic/gin"
)

func Allow(roles ...Role) func(ctx *gin.Context) {
	return func(ctx *gin.Context) {
		id, errT := common.CheckToken(ctx.GetHeader("Authorization"))
		if errT != nil {
			ctx.JSON(http.StatusConflict, gin.H{"error": errT})
			ctx.AbortWithStatus(http.StatusConflict)
			return
		}
		user, err := FindUserById(id)
		if err != nil {
			ctx.JSON(http.StatusConflict, gin.H{"error": err})
			return
		}
		ctx.Set("user", user)
		allowed := false
		for _, role := range roles {
			if role == user.Role {
				allowed = true
			}
		}
		if len(roles) == 0 {
			allowed = true
		}
		if user.Role == Root {
			allowed = true
		}

		if allowed {
			ctx.Next()
		} else {
			ctx.JSON(http.StatusForbidden, "权限不足")
			ctx.Abort()
		}
	}
}
